<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="50px">

            <el-form-item label="网关" prop="gatewayId">
                <gateway-select @changeGateway="changeGateway"/>
            </el-form-item>

        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['business:sensor:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['business:sensor:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['business:sensor:remove']"
                >删除
                </el-button>
            </el-col>
            <!--      <el-col :span="1.5">-->
            <!--        <el-button-->
            <!--          type="warning"-->
            <!--          plain-->
            <!--          icon="el-icon-download"-->
            <!--          size="mini"-->
            <!--          @click="handleExport"-->
            <!--          v-hasPermi="['business:sensor:export']"-->
            <!--        >导出</el-button>-->
            <!--      </el-col>-->
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="sensorList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <!--      <el-table-column label="信息点ID" align="center" prop="sensorId" />-->
            <el-table-column label="序号" align="center" type="index" :index="calculateIndex"/>
            <el-table-column label="网关" align="center" prop="gatewayName"/>
            <el-table-column label="名称" align="center" prop="sensorName"/>
            <el-table-column label="站号" align="center" prop="siteNumber"/>
            <el-table-column label="位置" align="center" prop="position"/>
            <el-table-column label="数值" align="center" prop="sensorValue"/>
            <el-table-column label="类型" align="center" prop="typeName"/>
            <el-table-column label="网关状态" align="center" prop="serverOnline">
                <template slot-scope="scope">
                    <svg-icon v-if="scope.row.serverOnline === '1'" icon-class="wifi-online"
                              style="width: 4em; height: 4em;"
                    />
                    <svg-icon v-if="scope.row.serverOnline === '0'" icon-class="wifi-offline"
                              style="width: 4em; height: 4em;"
                    />
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['business:sensor:edit']"
                    >修改
                    </el-button>

                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['business:sensor:remove']"
                    >删除
                    </el-button>
                    <el-button size="mini" type="text" icon="el-icon-setting"
                               @click="showDialog(scope.row, scope.$index)"
                    >
                        高级
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改信息点对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body v-dialogDrag>
            <el-form ref="form" :model="form" :rules="rules" label-width="85px" size="small">

                <el-form-item label="网关" prop="gatewayId">
                    <el-select v-model="form.gatewayId"
                               placeholder="请选择网关"
                    >
                        <el-option
                            v-for="item in gatewayListOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="类型" prop="sensorType">
                    <el-cascader
                        v-model="form.sensorType"
                        :options="sensorTypeList"
                        :props="{emitPath:false}"
                        @change="changeSensorType"
                    ></el-cascader>
                </el-form-item>

                <el-form-item label="名称" prop="sensorName">
                    <el-input v-model="form.sensorName" placeholder="请输入信息点名称"/>
                </el-form-item>

                <el-form-item label="站号" prop="siteNumber">
                    <el-input v-model="form.siteNumber" placeholder="请输入站号"/>
                </el-form-item>

                <el-form-item label="位置" prop="position">
                    <el-input v-model="form.position" placeholder="请输入寄存器位置"/>
                </el-form-item>

                <el-form-item label="单位" prop="unit">
                    <el-input v-model="form.unit" placeholder="请输入单位"/>
                </el-form-item>

                <el-form-item label="缩放倍数" prop="weight">
                    <el-select v-model="form.weight"
                               placeholder="缩放倍数"
                    >
                        <el-option
                            v-for="item in dict.type.biz_weight"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="数值类型" prop="valueType">
                    <el-select v-model="form.valueType"
                               placeholder="数值类型"
                    >
                        <el-option
                            v-for="item in dict.type.biz_value_type"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="寄存器个数" prop="registerSize">
                    <el-col :span="16">
                        <el-input v-model="form.registerSize"
                                  placeholder="请输入寄存器个数"
                                  type="number"
                                  @input="registerSizeChange(arguments[0], 10)"
                                  @change="registerSizeChange(arguments[0], 10)"
                        />
                    </el-col>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button size="small" type="primary" @click="submitForm">{{ buttonText }}</el-button>
                <el-button size="small" @click="cancel">取 消</el-button>
            </div>
        </el-dialog>


        <el-dialog :visible.sync="open2" width="500px" append-to-body fullscreen>

            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="实时读取" name="first">
                    <SensorSet :sensor="form" :key="key"/>
                </el-tab-pane>
                <el-tab-pane label="采集设置" name="second">
                    <SensorRead :sensor="form" :key="key"/>
                </el-tab-pane>
                <el-tab-pane label="展示设置" name="show">
                    <SensorConfig :sensor="form" :key="key"/>
                </el-tab-pane>
                <el-tab-pane label="数值转换" name="convert">
                    <SensorConvert :sensor="form" :key="key"/>
                </el-tab-pane>
                <el-tab-pane label="报警设置" name="warn">
                    <SensorWarn :sensor="form" :key="key"/>
                </el-tab-pane>
            </el-tabs>

            <el-form size="small">
                <el-form-item label="快捷">
                    <el-row :gutter="10" class="mb8">
                        <el-col :span="1.5">
                            <el-button type="success" size="small" @click="prev">上一个</el-button>
                        </el-col>
                        <el-col :span="1.5">
                            <el-button type="success" size="small" @click="next">下一个</el-button>
                        </el-col>
                    </el-row>
                </el-form-item>
            </el-form>

            <!--      <div slot="footer" class="dialog-footer" v-if="this.activeName === 'setting'">-->
            <!--        <el-button size="mini" type="primary" @click="submitForm">确 定</el-button>-->
            <!--      </div>-->
        </el-dialog>

    </div>
</template>

<script>

import { pageListSensor, getSensor, delSensor, addSensor, updateSensor } from '@/api/equipment/sensor'

import { listSensorType } from '@/api/system/sensorType'
import gatewaySelect from '../../common/GatewaySelect.vue'
import typeSelect from '../../common/typeSelect'
import '@/utils/directives.js'

import SensorSet from './set'
import SensorRead from './read'
import SensorConfig from './config'
import SensorConvert from './convert'
import SensorWarn from './warn'

const common = require('@/api/common/common')

export default {
    name: 'Sensor',
    dicts: ['biz_value_type', 'biz_weight'],
    components: {
        gatewaySelect,
        typeSelect,
        SensorSet,
        SensorRead,
        SensorConfig,
        SensorConvert,
        SensorWarn
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 信息点表格数据
            sensorList: [],
            // 弹出层标题
            title: '',
            buttonText: '',
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                sensorName: null,
                deployment: null,
                siteNumber: null,
                position: null,
                sensorType: null,
                gatewayId: null
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                gatewayId: [
                    { required: true, message: '请选择网关', trigger: 'blur' }
                ],
                sensorName: [
                    { required: true, message: '请输入信息点名称', trigger: 'blur' }
                ],
                siteNumber: [
                    { required: true, message: '请输入站号', trigger: 'blur' }
                ],
                position: [
                    { required: true, message: '请输入寄存器位置', trigger: 'blur' }
                ],
                valueType: [
                    { required: true, message: '请选择数值类型', trigger: 'blur' }
                ]
            },
            gatewayList: [],
            sensorTypeList: [],
            open2: false,

            currentGatewayId: null,
            // 当前网关编号
            currentGatewayNumber: null,

            // 用于修改回显所属网关
            gatewayListOption: [],

            messageObj: {},
            currentIndex: null,

            activeName: 'first',
            key: 0
        }
    },
    created() {
        this.getSensorTypeList()
    },
    methods: {

        handleClick(tab, event) {
            this.key += 1
        },

        registerSizeChange(val, maxNum) {
            let value = Number(val)
            this.$nextTick(() => {
                let num = Math.min(value, maxNum)
                if (num <= 0) {
                    this.form.registerSize = 1
                } else {
                    this.form.registerSize = num
                }
            })
        },

        changeSensorType(newVal) {
            this.form.sensorType = newVal
        },

        prev() {
            if (this.currentIndex > 0) {
                this.currentIndex--
            } else {
                this.$message.warning('已经是第一个了')
            }

            let data = this.sensorList[this.currentIndex]

            this.form = data

            this.form.sensorNewValue = null

            this.currentGatewayNumber = data.gatewayNumber
        },
        next() {
            if (this.currentIndex < this.sensorList.length - 1) {
                this.currentIndex++
            } else {
                this.$message.warning('已经是最后一个了')
            }

            let data = this.sensorList[this.currentIndex]

            this.form = data

            this.form.sensorNewValue = null
            this.currentGatewayNumber = data.gatewayNumber
        },
        calculateIndex(index) {
            const pageNum = this.queryParams.pageNum
            const pageSize = this.queryParams.pageSize
            return index + 1 + (pageNum - 1) * pageSize
        },

        // 获取所有的信息点类型
        getSensorTypeList() {
            this.sensorTypeList = []
            listSensorType().then(response => {
                // console.log(response)
                for (let item of response.data) {
                    if (item.parentId === 0) {
                        let level1 = {
                            value: item.id,
                            label: item.typeName,
                            children: []
                        }
                        this.sensorTypeList.push(level1)
                    }
                }

                for (let item of response.data) {
                    let obj = this.sensorTypeList.find((level1) => {
                        return level1.value === item.parentId
                    })
                    if (obj !== undefined) {
                        let level2 = {
                            value: item.id,
                            label: item.typeName
                        }
                        obj.children.push(level2)
                    }
                }

            })
        },

        // 接收子组件传递的消息
        changeGateway(obj) {
            this.gatewayListOption = obj.gatewayListOption
            // this.queryParams.projectId = obj.projectId
            this.queryParams.gatewayId = obj.gatewayId
            this.getList()
        },
        /** 查询信息点列表 */
        getList() {
            this.loading = true
            pageListSensor(this.queryParams).then(response => {
                this.sensorList = response.rows
                this.total = response.total
                this.loading = false
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                sensorId: null,
                sensorName: null,
                deployment: null,
                siteNumber: null,
                position: null,
                sensorType: null,
                sensorValue: null,
                showState: null,
                gatewayId: null,
                warnEnable: null,
                warnParam: null,
                curveGraphState: null,
                minValue: null,
                maxValue: null,
                weight: '1',
                valueType: 'int',
                registerSize: 1
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm('queryForm')
            this.handleQuery()
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.sensorId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset()
            this.open = true
            this.title = '添加信息点'
            this.buttonText = '添 加'
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const sensorId = row.sensorId || this.ids
            getSensor(sensorId).then(response => {
                this.form = response.data
                this.title = '修改信息点'
                this.buttonText = '修 改'
                this.open = true
            })
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    if (this.form.sensorId != null) {
                        updateSensor(this.form).then(response => {
                            this.$modal.msgSuccess('修改成功')
                            this.open = false
                            this.getList()
                        })
                    } else {

                        // console.log(this.form)

                        addSensor(this.form).then(response => {
                            this.$modal.msgSuccess('新增成功')
                            this.open = false
                            this.getList()
                        })
                    }
                }
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const sensorIds = row.sensorId || this.ids
            this.$modal.confirm('是否确认删除信息点编号为"' + sensorIds + '"的数据项？').then(function() {
                return delSensor(sensorIds)
            }).then(() => {
                this.getList()
                this.$modal.msgSuccess('删除成功')
            }).catch(() => {
            })
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('business/sensor/export', {
                ...this.queryParams
            }, `sensor_${new Date().getTime()}.xlsx`)
        },

        showDialog(row, index) {
            this.key += 1
            this.currentIndex = index
            this.open2 = true
            this.form = row
        }

    }
}
</script>

<style scoped></style>
